package com.star.exception;

import com.star.result.API;
import com.star.result.ApiRes;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

import static org.springframework.http.HttpStatus.*;

/**
 * GlobalDefaultExceptionHandler.
 *
 * @author cuizuoli
 */
@RestControllerAdvice
public class GlobalDefaultExceptionHandler {

    @ResponseStatus(INTERNAL_SERVER_ERROR)
    @ExceptionHandler(Exception.class)
    public ApiRes handleException(Exception e) {
        return API.error(ExceptionUtils.getMessage(e));
    }

    @ResponseStatus(NOT_FOUND)
    @ExceptionHandler(NoHandlerFoundException.class)
    public ApiRes handleNoHandlerFoundException(Exception e) {
        return API.error(ExceptionUtils.getMessage(e));
    }

    @ResponseStatus(BAD_REQUEST)
    @ExceptionHandler(ServiceException.class)
    public ApiRes handleServiceException(ServiceException e) {
        return API.error(e.getCode(), e.getMessage());
    }

    @ResponseStatus(INTERNAL_SERVER_ERROR)
    @ExceptionHandler(SystemException.class)
    public ApiRes handleSystemException(SystemException e) {
        return API.error(e.getCode(), e.getMessage());
    }
}
